package com.samphanie.ane.core.security.config;

import com.samphanie.ane.core.security.handler.CustomAuthenticationFailureHandler;
import com.samphanie.ane.core.security.handler.CustomAuthenticationSuccessHandler;
import com.samphanie.ane.core.security.handler.CustomLogoutSuccessHandler;
import com.samphanie.ane.core.security.utils.SecurityCoreConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.stereotype.Component;

/**
 * @Author ZSY
 * @createTime 2021/3/13 17:28
 * <p>
 * 表单登录配置
 */
@RequiredArgsConstructor
@Component
public class FormAuthenticationConfig {

    private final CustomAuthenticationFailureHandler failureHandler;
    private final CustomAuthenticationSuccessHandler successHandler;
    private final CustomLogoutSuccessHandler logoutSuccessHandler;

    /**
     * 密码登录配置
     *
     * @param http
     * @throws Exception
     */
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(req -> req.anyRequest().authenticated())
                .formLogin(formLogin -> formLogin
                        .loginPage(SecurityCoreConstants.DEFAULT_UNAUTHENTICATION_URL)
                        .loginProcessingUrl(SecurityCoreConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
                        .defaultSuccessUrl("/")
                        .failureUrl("/login?error")
                        .successHandler(successHandler)
                        .failureHandler(failureHandler)
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutSuccessHandler(logoutSuccessHandler)
                )
                .rememberMe(remember -> remember
                                .key("someSecret")
                                .tokenValiditySeconds(30 * 24 * 3600)
                                //  .rememberMeCookieName("someKeyToRemember")
                )
                // 显示浏览器对话框，需要禁用 CSRF ，或添加路径到忽略列表
                .httpBasic(Customizer.withDefaults());
    }

}
